﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OliveChess
{
    class TranspositionTable
    {
        private Dictionary<String, TranspTableEntry> TT;
        private int maxSize;

        public TranspositionTable()
        {
            TT = new Dictionary<string, TranspTableEntry>();
            maxSize = 0;
        }

        internal void Clear()
        {
            TT.Clear();
        }

        internal bool TryGetValue(string pfen, out TranspTableEntry entry)
        {
            return TT.TryGetValue(pfen, out entry);
        }

        internal void Add(string pfen, TranspTableEntry entry)
        {
            try
            {
                TT.Add(pfen, entry);
                maxSize++;
            }
            catch (Exception e)
            {
                Console.WriteLine("Entry already in TT !" + e.Message);
            }
        }

        internal void SetMaxSize(int size)
        {
            TT.Clear();
            maxSize = size;
        }

        // get the hash is x permill full (uci protocol complient)
        internal int GetHashfull()
        {
            if (maxSize == 0) 
                return 0; 
            return (1000*TT.Count)/maxSize;
        }

        // get the hash is x permill full (uci protocol complient)
        internal void DisplayHashfull()
        {
            if (maxSize > 0) 
                Console.WriteLine("info hashfull " + (1000 * TT.Count) / maxSize);
        }


        

            /*
        // Try to add
        // if already exists, keep the min eval
        internal void AddMin(string pfen, int score)
        {
            int oldScore = 0;
            if (TT.TryGetValue(pfen, out oldScore))
            {
                if (score < oldScore)
                {
                    TT[pfen] = score;
                    Console.WriteLine("TT entry updated to " + score);
                }
            } 
            else
            {
                TT.Add(pfen, score);
            }
        }


        // Try to add
        // if already exists, keep the max eval
        internal void AddMax(string pfen, int score)
        {
            int oldScore = 0;
            if (TT.TryGetValue(pfen, out oldScore))
            {
                if (score > oldScore)
                {
                    TT[pfen] = score;
                    Console.WriteLine("TT entry updated to " + score);
                }
            }
            else
            {
                TT.Add(pfen, score);
            }
        }
            */
    }
}
